package com.example.intentdemo;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import androidx.activity.EdgeToEdge;
import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

public class MainActivity extends AppCompatActivity {
    private TextView tvWelcome;
    private TextView tvInterestResult;
    private Button btnGoInterest;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 1. 注册回调：接收从InterestActivity返回的数据
        ActivityResultLauncher<Intent> interestLauncher = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                new ActivityResultCallback<ActivityResult>() {
                    @Override
                    public void onActivityResult(ActivityResult result) {
                        // 校验结果是否有效（RESULT_OK表示目标页面成功返回数据）
                        if (result.getResultCode() == RESULT_OK) {
                            Intent data = result.getData();
                            if (data != null) {
                                // 获取回传的兴趣数据
                                String selectedInterest = data.getStringExtra("selected_interest");
                                // 显示在主页
                                tvInterestResult.setText("你的兴趣：" + selectedInterest);
                            }
                        }
                    }
                }
        );

        // 初始化控件
        tvWelcome = findViewById(R.id.tv_welcome);
        tvInterestResult = findViewById(R.id.tv_interest_result);
        btnGoInterest = findViewById(R.id.btn_go_interest);

        // 接收登录页传递的用户名
        // 第二个参数为默认值：若未获取到数据，显示"游客"
        String username = getIntent().getStringExtra("username");
        if (username == null || username.isEmpty()) {
            username = "游客";
        }
        // 显示欢迎语
        tvWelcome.setText("欢迎，" + username + "！");
        // 2. 点击“选择兴趣”按钮，跳转到InterestActivity
        btnGoInterest.setOnClickListener(v -> {
            Intent intent = new Intent(MainActivity.this, InterestActivity.class);
            // 用launch()启动，而非startActivity()（配合回调使用）
            interestLauncher.launch(intent);
        });
    }
}